import json
import string
from tokenize import String
from typing import List

from sqlalchemy.exc import SQLAlchemyError

from common.ApiResponse import ApiResponse
from common.BaseResponse import BaseResponse
from common.ErrorCode import ErrorCode
from models import App, UserAnswer, Question, ScoringResult, db


def doTestScore(choices: list[str], app: App, id: int) -> UserAnswer:
    appId = app.id
    question = Question.query.filter(Question.appId == appId).first()
    scoringResultList: list[ScoringResult] = ScoringResult.query.filter(ScoringResult.appId == appId).filter(ScoringResult.isDelete==0).all()
    if not isinstance(question, Question):
        print("question参数类型错误哦")
        baseResponse = BaseResponse.from_error_code(ErrorCode.OPERATION_ERROR)
        return ApiResponse.error_from_baseResponse(baseResponse=baseResponse, data="参数类型错误")

    if not isinstance(scoringResultList, list):
        print("scoringResultList 参数不是列表类型哦")
        baseResponse = BaseResponse.from_error_code(ErrorCode.OPERATION_ERROR)
        return ApiResponse.error_from_baseResponse(baseResponse=baseResponse, data="参数类型错误")
        # 检查列表中的每个元素是否为 ScoringResult 类型
    for item in scoringResultList:
        if not isinstance(item, ScoringResult):
            print("scoringResultList 列表中的元素类型错误哦")
            baseResponse = BaseResponse.from_error_code(ErrorCode.OPERATION_ERROR)
            return ApiResponse.error_from_baseResponse(baseResponse=baseResponse, data="参数类型错误")
    optionCount = dict()
    questionContent = question.questionContent
    questionContentList = json.loads(questionContent)
    for index, item in enumerate(questionContentList):
        title = item["title"]
        options = item["options"]
        answer = choices[index]
        for option in options:
            if option.get('key') == answer:
                result = option.get('result')
                optionCount[result] = optionCount.get(result, 0) + 1
    maxScore = 0
    maxScoringResult = scoringResultList[0]
    for index, scoringResult in enumerate(scoringResultList):
        resultProp: str = scoringResult.resultProp
        resultPropList = resultProp.split(",")
        score = 0
        for result in resultPropList:
            score += optionCount.get(result, 0)
        if score > maxScore:
            maxScore = score
            maxScoringResult = scoringResult
    try:
        userAnswer:UserAnswer = UserAnswer.query.get(id)
        userAnswer.appId = maxScoringResult.appId
        userAnswer.appName = app.appName
        userAnswer.score = app.scoringStrategy
        userAnswer.choices = json.dumps(choices, ensure_ascii=False, indent=4)
        userAnswer.resultName = maxScoringResult.resultName
        userAnswer.resultId = maxScoringResult.id
        userAnswer.resultDesc = maxScoringResult.resultDesc
        userAnswer.resultPicture = maxScoringResult.resultPicture
        db.session.commit()
        return userAnswer
    except SQLAlchemyError as e:
        print(f"测评类用户添加失败:{str(e)}")
        db.session.rollback()
        baseResponse = BaseResponse.from_error_code(ErrorCode.OPERATION_ERROR)
        return ApiResponse.error_from_baseResponse(baseResponse=baseResponse, data=str(e))
